const { Sequelize, DataTypes } = require('sequelize');

// 加载配置
const config = require('./config/config.default.js')({ name: 'lingxi-system' });

// 创建数据库连接
const sequelize = new Sequelize(config.sequelize.database, config.sequelize.username, config.sequelize.password, {
  host: config.sequelize.host,
  port: config.sequelize.port,
  dialect: config.sequelize.dialect,
  timezone: config.sequelize.timezone,
  define: config.sequelize.define,
  logging: false, // 关闭SQL日志
});

// 定义销售订单模型
const SalesOrder = sequelize.define('sales_order', {
  id: {
    type: DataTypes.BIGINT,
    primaryKey: true,
    autoIncrement: true
  },
  orderId: {
    type: DataTypes.STRING,
    allowNull: false,
    field: 'order_id'
  },
  orderCode: {
    type: DataTypes.STRING,
    field: 'order_code'
  },
  purchaserName: {
    type: DataTypes.STRING,
    field: 'purchaser_name'
  },
  supplierName: {
    type: DataTypes.STRING,
    field: 'supplier_name'
  },
  orderStatus: {
    type: DataTypes.STRING,
    field: 'order_status'
  },
  orderAmount: {
    type: DataTypes.DECIMAL(10, 2),
    field: 'order_amount'
  },
  orderTime: {
    type: DataTypes.DATE,
    field: 'order_time'
  },
  platformSource: {
    type: DataTypes.STRING,
    field: 'platform_source'
  },
  createdAt: {
    type: DataTypes.DATE,
    field: 'created_at'
  },
  updatedAt: {
    type: DataTypes.DATE,
    field: 'updated_at'
  }
}, {
  tableName: 'sales_orders',
  timestamps: true,
  underscored: true
});

async function checkSalesOrders() {
  try {
    // 测试数据库连接
    await sequelize.authenticate();
    console.log('✅ 数据库连接成功');
    
    // 查询最新的销售订单
    console.log('\n🔍 查询最新的销售订单...');
    const orders = await SalesOrder.findAll({
      order: [['createdAt', 'DESC']],
      limit: 10
    });
    
    console.log(`📋 找到 ${orders.length} 条销售订单记录:`);
    orders.forEach((order, index) => {
      console.log(`\n订单 ${index + 1}:`);
      console.log(`  订单ID: ${order.orderId}`);
      console.log(`  采购人: ${order.purchaserName}`);
      console.log(`  供应商: ${order.supplierName}`);
      console.log(`  订单金额: ${order.orderAmount}`);
      console.log(`  订单状态: ${order.orderStatus}`);
      console.log(`  平台来源: ${order.platformSource}`);
      console.log(`  创建时间: ${order.createdAt}`);
    });
    
    // 统计订单总数
    const count = await SalesOrder.count();
    console.log(`\n📊 销售订单总数量: ${count}`);
    
  } catch (error) {
    console.error('❌ 查询销售订单时出错:', error);
  } finally {
    await sequelize.close();
  }
}

checkSalesOrders();